<template>
  <div>
    <x-header title="下单" style="background-color: #000;"><a slot="right"></a></x-header>
    <!--下单页面-->
    <div class="list">
      <group>
        <div style="margin: 1rem 0 0 1rem;">收货地址</div>
        <popup-radio title="" :options="options1" v-model="addressId" @on-change="optionsChange"></popup-radio>
      </group>
      <div class="company" v-for="(v,index) in order">
        <h5 class="company-title"><i class="iconfont icon-dianpu"></i>{{v.company_name}}</h5>
        <div class="foodItem" v-for="(v1,index1) in v.shoppingCartList">
          <div class="item-img">
            <img :src="config1.fileUrl+v1.img_url+'?x-oss-process=image/resize,w_60,h_60'" alt="">
          </div>
          <div class="item-text">
            <div class="name">
              <div class="name-left">
                <label :for="v1.id">{{v1.goods_name}}</label>
                <p v-show="v1.norms.norm">规格：{{v1.norms.norm}}</p>
              </div>
              <div class="name-right">
                <span class="remove" @click="del(v,index)"><i class="fa fa-trash"></i></span>
              </div>
            </div>
            <div class="name-bottom">
              <div class="price">
                ￥<span>{{(v1.norms.price*1).toFixed(2)}}</span>
              </div>
              <div class="num">
                X <span style="font-size: 1rem;">{{v1.num}}</span>
                <!--<x-number title="" v-model="v1.num" :min="0" @on-change="numChange(v1)" style="padding:0;" width="30px"></x-number>-->
              </div>
            </div>
          </div>
        </div>
        <div style="font-size: 0.8rem;padding: 0 1rem 1rem 1rem;">
          <!--<div style="margin: 0.5rem 1rem;">开具发票：-->
            <!--<span @click="v.is_open_invoice=v.is_open_invoice==='1'?'0':'1'">-->
              <!--<icon :type="v.is_open_invoice==='1'?'success':'circle'"></icon>-->
              <!--<span style="vertical-align: middle">{{v.is_open_invoice==='1'?'是':'否'}}</span>-->
            <!--</span>-->
          <!--</div>-->
          <x-input title="" placeholder="买家留言..." v-model="v.remark"></x-input>
        </div>
      </div>
    </div>
    <!--=============================================================================================================-->
    <!--底部计算框-->
    <div class="bottomCalc">
      <span>合计：<span class="calc">￥{{totalPrice.toFixed(2)}}</span></span>
      <span class="btn" @click="submitOrder">提交订单</span>
    </div>
  </div>
</template>

<script>
  import bus from '../../../utils/bus'
  import { Group, PopupRadio } from 'vux'
  export default {
    components: {
      Group,PopupRadio
    },
    data() {
      return {
        order: [],
        totalPrice: 0,
        addList: [], // 收货地址列表,
        addressId: '', // 选择的收货地址
        defaultId: '', // 默认收货地址
        isInvoice: '', // 是否开具发票

        options1: [],
      }
    },
    methods: {
      // 信息提示
      msg(str){
        this.$vux.toast.show({
          type: 'text',
          text: str,
          position: 'default',
          time: 800,
        });
      },
      // 处理商品并按供应商归类
      dispose(arr) {
        let obj = {};
        // 1.循环列出不同供应商id对应的值
        arr.forEach((item, index) => {
          obj[item.supplyId] = item;
        });
        // 2.根据供应商id分类商品
        let list = []; // 存放所有供应商及内部商品
        for (let i in obj) {
          let arr1 = []; // 存放同一供应商的商品
          arr.forEach((it, index) => {
            if (it.supplyId === i) {
              arr1.push({
                goods_id: it.goodsId,
                goods_name: it.goodsName,
                supply_id: it.supplyId,
                norm: it.norms,
                price: it.price,
                num: it.num,
                remark: it.remark,
              });
            }
          });
          list.push({
            supply_id: obj[i].supplyId,
            is_open_invoice: '0', // 是否开具发票
            address_id: this.defaultId, // 选择的收货地址id,
            remark: '', // 订单备注
            order_detail: arr1, // 商品列表
          })
        }
        return list;
      },
      // 购物车过来的商品处理
      disposeForCart(arr){
        let obj = {};
        // 1.循环列出不同供应商id对应的值
        arr.forEach((item, index) => {
          obj[item.supplyId] = item;
        });
        // 2.根据供应商id分类商品
        let list = []; // 存放所有供应商及内部商品
        for (let i in obj) {
          let arr1 = []; // 存放同一供应商的商品
          arr.forEach((it, index) => {
            if (it.supplyId === i) {
              arr1.push({
                goods_id: it.goods_id,
                goods_name: it.goods_name,
                supply_id: it.supply_id,
                norm: it.norms,
                price: it.norms.price,
                num: it.num,
                cartId: it.id,
                remark: it.remark,
              });
            }
          });
          list.push({
            supply_id: obj[i].supplyId,
            is_open_invoice: '0', // 是否开具发票
            address_id: this.defaultId, // 选择的收货地址id,
            remark: '', // 订单备注
            order_detail: arr1, // 商品列表
          })
        }
        return list;
      },
      // 获取收货地址
      getAddress() {
        this.$vux.loading.show();
        this.config1.post('/purchasers/app/order/getDefaultAddress', {}).then(res => {
          this.$vux.loading.hide();
          if (res.data.code === '0') {
            this.addList = res.data.purchasersAddressList;
            this.options1 = [];
            this.addList.forEach(it => {
              if (it.is_default === '1') {
                this.defaultId = it.id;
                this.addressId = it.id;
              }
              this.options1.push({
                key: it.id,
                value: it.province+it.city+it.area+it.detail_address,
              })
            });
            if (!this.defaultId) {
              this.defaultId = this.addList[0].id;
              this.addressId = this.addList[0].id;
            }
            if(this.$route.query['sign']==='cart'){
              // this.order = this.disposeForCart(JSON.parse(this.$route.query['order']));
              this.order = JSON.parse(this.$route.query['order']);
              console.log(this.order)
            }else{
              // this.order = this.dispose(JSON.parse(this.$route.query['order']));
              this.order = JSON.parse(this.$route.query['order']);
              console.log(this.order, '直接下单的')
            }
            this.calcTotal();
          } else {
            this.msg(this.config1.handleError(res.data));
          }
        })
      },
      // 地址改变
      optionsChange(value){
        this.addressId = value;
      },
      // 进入店铺
      setDefault(v) {
      },
      // 移除
      del(v, index) {
        this.order.splice(index, 1);
        this.calcTotal();
      },
      // 计算订单总价
      calcTotal(){
        let p = 0;
        this.order.forEach(it=>{
          it.shoppingCartList.forEach(item=>{
            p += item.norms.price * item.num;
          })
        });
        this.totalPrice = p;
      },
      // 提交订单
      submitOrder() {
        if (!this.order.length) {
          return
        }
        let obj = [];
        this.order.forEach(it=>{
          let arr = [];
          it.shoppingCartList.forEach(item=>{
            arr.push({
              goods_id: item.goods_id,
              goods_name: item.goods_name,
              supply_id: item.supply_id,
              norm: item.norms,
              price: item.norms.price,
              num: item.num,
              cartId: item.id,
              remark: item.remark||'',
            })
          });
          obj.push({
            supply_id: it.id || it.supply_id,
            is_open_invoice: it.is_open_invoice,
            address_id: this.addressId,
            remark: it.remark,
            order_detail: arr,
          })
        });
        console.log(obj)
        this.$vux.loading.show();
        this.config1.post('/purchasers/app/order/placeOrder', {goodsJson: JSON.stringify(obj)}).then(res => {
          this.$vux.loading.hide();
          if (res.data.code === '0') {
            this.msg(res.data.message);
            this.$router.push('/project1/view2/order-success');
            bus.$emit('addFood','msg');
          } else {
            this.msg(this.config1.handleError(res.data));
          }
        })
      },
    },
    mounted() {
      this.getAddress();
    }
  }
</script>

<style scoped lang="less">
  .list {
    width: 100%;
    margin: 1rem auto;
    position: absolute;
    text-align: left;
    padding-bottom:80px;
    .company {
      border-radius: 8px;
      box-shadow: 0 0 5px 0 silver;
      background: #fff;
      margin: 1rem;
      .company-title {
        padding:0.5rem;
        .iconfont{
          color:#33bb99;
          padding-right:5px;
          font-size:0.9rem;
          font-weight: normal;
        }
      }
      .foodItem {
        font-size: 0.8rem;
        clear: both;
        padding: 1rem 1rem 1rem 0.5rem;
        /*height:65px;*/
        border-top: 1px solid #33bb99;
        display: flex;
        .item-input{
          width:10%;
          float: left;
          padding-top: 20px;
          padding-left:0;
          position: relative;
          input{
            position: absolute;
            width: 100%;
            height: 100%;
            top:0;
            left: 0;
            opacity: 0;
          }
        }
        .item-img{
          width: 25%;
          overflow: hidden;
          float: left;
          text-align: center;
          img{
            height:60px;
            width:60px;
            /*margin-top: 10px;*/
          }
        }
        .item-text{
          width: 75%;
          /*float: left;*/
          .name{
            width: 100%;
            line-height:20px;
            height:40px;
            display: flex;
            justify-content: space-between;
            .name-left{
              label{
                font-weight: 700;
              }
              p{
                color:#999;
                font-size: 0.6rem;
              }
            }
            .name-right{
              text-align: center;
              font-size:1rem;
              color:#ccc;
            }
          }
          .name-bottom{
            display: flex;
            justify-content: space-between;
            .price{
              color: #ff0000;
              font-weight: 700;
              line-height:30px;
              span{
                font-size: 1rem;
              }
            }
            .num{
            }
          }
        }
      }
    }
    .clearCart{
      float: right;cursor: pointer;
      &:hover{
        color: red;
      }
    }
  }
  .bottomCalc{
    position: fixed;
    width: 100%;
    left: 0;
    bottom: 0;
    border-top: 1px solid #eee;
    padding-left: 1rem;
    line-height: 48px;
    display: flex;
    justify-content: flex-end;
    box-sizing: border-box;
    background: #fff;
    .calc{
      color: #ff0000;
      font-weight: 700;
      padding-right:1rem;
    }
    .btn{
      height:100%;
      padding: 0 1rem;
      background: #33bb99;
      color:#fff;
      display: inline-block;
      /*letter-spacing: 0.2rem;*/
    }
  }
</style>
